// 1. create
// 2. new
// 3. instanceof
// 4. clone
// 5. deepClone
// 6. extends
// 7. valueOf
// 8. calculate object size

Object.myCreate = function (obj) {
    function fn() { }
    fn.prototype = obj; // 新对象 能拿到对象的所有方法
    return new fn()
}
console.log(Object.myCreate({a:1}))
console.log(Object.create({a:1}))

function myNew(fn, ...args) {
    let newFn = Objcet.create(fn.prototype) // 原型上的方法
    let result = fn.call(newFn, ...args) // this 上的方法
    return result instanceof Object ? result : newFn; // 如果构造函数返回了一个对象，则使用这个对象，否则使用新创建的对象 
}

function myInstanceOf(obj, Obj){
  let objPrototype = Object.getPrototypeOf(obj);
  let ObjPrototype = Obj.prototype;
  while(true){
    if(objPrototype === null) return false
    if(objPrototype === ObjPrototype) return true;
    objPrototype = Object.getPrototypeOf(objPrototype)
  }
}
// 示例
function A() {}
let a = new A();

console.log(myInstanceOf(a, A), '---'); // true
console.log(myInstanceOf(a, Object)); // true
console.log(myInstanceOf(a, Array)); // false

// 继承的写法

function deepClone(obj, weakMap = new WeakMap()) {
  if (obj instanceof RegExp) {
    return new RegExp(obj)
  }
  if (obj instanceof Date) {
    return new Date(obj)
  }
  if (obj === null || typeof obj !== 'object') {
    return obj
  }
  const Constructor = obj.constructor;
  const res = new Constructor()
  if (weakMap.has(obj)) {
    return weakMap.get(obj)
  }
  weakMap.set(obj, res)

  Object.keys(obj).forEach((key) => {
    if (obj.hasOwnProperty(key)) {
      res[key] = deepClone(obj[key], weakMap)
    }
  })
  return res;
}
// 示例使用
const original = {
  number: 1,
  bool: false,
  string: 'string',
  date: new Date(),
  regex: /regex/,
  array: [1, 2, 3],
  object: {
    nested: 'nested'
  },
  func: function() { console.log('hello'); }
};

const copied = deepClone(original);
console.log(copied);


function clone(obj) {
  if (obj instanceof RegExp) {
    return new RegExp(obj)
  }
  if (obj instanceof Date) {
    return new Date(obj)
  }
  if (obj === null || typeof obj !== 'object') {
    return obj
  }
  const Constructor = obj.constructor;
  const res = new Constructor()

  Object.keys(obj).forEach((key) => {
    if (obj.hasOwnProperty(key)) {
      res[key] = obj[key]
    }
  })
  return res;
}
console.log(clone(original));


// 继承
function inherit(son,father){
    let newson = Objcet.create(father.prototype)
    son.prototype = newson;
    son.prototype.constructor = son 
}
function Fa(){}
function Son(...args){
    Fa.call(this, ...args)
    inherit(Son, Fa)
}

//使等式成立
var a = {
    n : 1,
    valueOf: function(){
        console.log(this.n)
        return this.n++
    }
}
console.log(a == 1 && a == 2 && a == 3)


